package com.gc.service;

import com.gc.common.JSONSerializer;
import com.gc.common.RpcDecoder;
import com.gc.common.RpcEncoder;
import com.gc.common.RpcRequest;
import com.gc.handler.UserServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {


    @Override
    public String sayHello(String msg) {
        System.out.println("调用成功--参数：" + msg);
        return "success";
    }


    public static void startServer(String ip, int port) throws InterruptedException {
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                       /* p.addLast(new StringDecoder());
                        p.addLast(new StringEncoder());*/
                       //设置编码
                        p.addLast(new StringEncoder());
                        p.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        //自定义处理类
                        p.addLast(new UserServerHandler());
                    }
                });
        bootstrap.bind(ip, port).sync();

    }


}
